<template>
  <div class="fullMain" style="height: calc(100% - 50px);overflow: scroll;">
    <div style="position:fixed; width:100%; z-index:999">
      <x-header :left-options="{backText: '',showBack: false}">
        {{memberSelectedInfo.detail.name}}
      </x-header>
    </div>
    <!--插入验证提示框-->
    <div v-transfer-dom>
      <alert v-model="isShowAlert"> {{alertText}}</alert>
    </div>
    <div class="mainBg"
         style="height: calc( 100% - 52px);background-color: white;margin-top: 46px;padding-bottom: 10px">
      <!--      <div class="chat_view" id="chat_view">-->
      <!--        <div style="height: 20px; width: 100%"></div>-->
      <div class="message_box" id="message_box" v-if="chatContent"
           style="height: calc( 100% - 15px);overflow: scroll;overflow-x: hidden;">
        <div v-for="(item,index) in chatContent" :key="index" style="margin-top: 5px">
          <!--                      <p class="content_time">{{item.time}}</p>-->
          <div :class="item.userId!==uid?left_head_box:right_head_box" style="background-color: white">
            <img :src="item.avatar" class="myHeadIcon"/><br>
            <span style="background-color: white;font-size: smaller;color: grey">{{item.name}}</span>
          </div>
          <div class="content_view_box">
            <!--      方框前的三角形-->
            <span :class="item.userId!==uid?left_triangle:right_triangle"></span>
            <div :class="item.userId!==uid?left_msg_box:right_msg_box">{{item.content}}</div>
          </div>
        </div>
      </div>
      <!--      </div>-->
    </div>
    <div class="chat_input">
      <!--      <div contenteditable="true" class="input_box" id="input_box" style="margin-right: 1px" @keyup.enter="sendFun"></div>-->
      <div contenteditable="true" class="input_box" id="input_box" style="margin-right: 1px"></div>
      <button class="send_bt" @click="sendMessage">发送</button>
    </div>
  </div>
</template>
<script>
  import {XHeader, TransferDom} from 'vux'
  import {mapState} from 'Vuex'
  import group from 'api/group'
  import user from 'api/user'
  import SockJS from 'sockjs-client'
  import Stomp from 'stompjs'
  import chat from 'api/chat'

  export default {
    name: 'G_group_chat',
    components: {
      XHeader,
    },
    data () {
      return {
        alertText: '',
        isShowAlert: false,
        chatContent: [],
        groupName: '',
        uid: '',//登陆者id
        uName: '',
        messageInput: '',

        //控制每条消息的显示样式
        left_head_box: 'left_head_box',
        right_head_box: 'right_head_box',
        left_triangle: 'left_triangle',
        right_triangle: 'right_triangle',
        left_msg_box: 'left_msg_box',
        right_msg_box: 'right_msg_box',

        stompClient: null,
      }
    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo
      }),
      ...mapState(['memberSelectedInfo']),
    },
    mounted () {
      this.connect()
      // let wholeName = this.groupPresent.detail.groupName
      // this.groupName = wholeName.slice(wholeName.lastIndexOf('-') + 1)
      // console.log('群信息', this.memberSelectedInfo)
    },
    directives: {
      TransferDom
    },
    watch: {
      chatContent (val) {
        let messageArea = document.querySelector('#message_box')
        const heightSpace = messageArea.scrollHeight - messageArea.scrollTop
        if (heightSpace == messageArea.clientHeight) {
          this.updateView(val.length)
        }
      }
    },
    // created () {
    //   // this.initWebSocket()
    //
    // },
    methods: {
      back () {
        this.$router.go(-1)
      },
      showAlert (alertText) {
        this.isShowAlert = true
        this.alertText = alertText
      },
      closeTip () {
        this.isShowAlert = false
        this.alertText = ''
      },
      toGroupMemberPage () {
        this.$router.push({name: 'G_group_member'})
      },

      connect () {
        // console.log('个人信息', this.userInfo)
        this.uid = this.userInfo.userId
        // console.log('12111111111111112', this.uid)
        const userName = this.userInfo.detail.name
        // console.log('用户名', userName)
        if (userName) {
          // console.log('建立连接')
          var socket = new SockJS('http://wsn2019.club:8085/chat')
          this.stompClient = Stomp.over(socket)
          this.stompClient.connect({}, this.onConnected, this.onError)
        }
        // event.preventDefault()
      },
      onConnected () {
        // console.log('连接中')
        // console.log('状态', this.stompClient.status)
        // const allGroups = await group.getGroupsBeIn()
        // console.log('所有群', allGroups)
        // if (allGroups.code === 1) {
        //   allGroups.data.forEach(item => {
        //     const gid = item.groupId
        //     // Subscribe to the Public Topic
        //     // TODO 对于该用户的每个群，都订阅一下，比如有群1,2,3，则
        //     this.stompClient.subscribe('/topic/'+gid, this.onMessageReceived)
        //   })
        // }
        // 接下来是订阅自己的账号，假设该用户id是123
        const uid = this.userInfo.userId
        // console.log(uid)
        this.stompClient.subscribe('/queue/privateMessage_' + uid, this.onMessageReceived)
        // Tell your username to the server
        // this.stompClient.send('/app/chat.addUser',
        //   {},
        //   JSON.stringify({sender: this.userInfo.userId, type: 'JOIN'})
        // )
        this.getHistoryLogs()
      },
      onError () {
        this.showAlert('Could not connect to WebSocket server. Please refresh this page to try again!')
      },
      // 私聊
      sendMessage () {
        const content_box = document.getElementById('input_box')
        var messageContent = content_box.textContent

        if (messageContent && this.stompClient) {
          var chatMessage = {
            sender: this.userInfo.userId,
            content: messageContent,
            type: 'SINGLE',
            receiver: this.memberSelectedInfo.userId
          }

          this.stompClient.send('/app/chat.sendMessage', {}, JSON.stringify(chatMessage))
          this.updateChatContent(null)
          content_box.textContent = ''
        }
        // event.preventDefault()
      },

      onMessageReceived (payload) {
        var message = JSON.parse(payload.body)
        var messageElement = document.createElement('li')

        // if (message.type === 'JOIN') {
        //   messageElement.classList.add('event-message')
        //   message.content = message.sender + ' joined!'
        // } else if (message.type === 'LEAVE') {
        //   messageElement.classList.add('event-message')
        //   message.content = message.sender + ' left!'
        // } else {
          console.log(payload.body)
          const msgBody = JSON.parse(payload.body)
          this.updateChatContent(msgBody)
        // }
      },
      updateChatContent (msgBody) {
        let msg = {}
        if (msgBody === null) {
          const content_box = document.getElementById('input_box')
          let messageContent = content_box.textContent
          msg = {
            userId: this.userInfo.userId,
            name: this.userInfo.detail.name,
            content: messageContent,
            avatar: this.userInfo.detail.avatar
          }
        } else {
          msg = {
            userId: Number(msgBody.sender),
            name: this.memberSelectedInfo.detail.name,
            content: msgBody.content,
            avatar: this.memberSelectedInfo.detail.avatar
          }
        }
        this.chatContent.push(msg)
      },
      updateView (msgCont) {
        console.log('消息个数', msgCont)
        let timer = setTimeout(function () {
          const numbers = $('#message_box>div').length
          console.log('div个数', numbers)
          if (msgCont === numbers) {
            console.log('相等了')
            let messageArea = document.querySelector('#message_box')
            messageArea.scrollTop = messageArea.scrollHeight
            clearInterval(timer)
          }
        }, 50)
        let messageArea = document.querySelector('#message_box')
        console.log('scrollTop222222222222222', messageArea.scrollTop)
        console.log('scrollHeight222222222222', messageArea.scrollHeight)
        console.log('clientHeight2222222', messageArea.clientHeight)
        const scrollSpace2 = messageArea.scrollHeight - messageArea.scrollTop
        console.log('差值222', scrollSpace2)
        // }
      },
      async getHistoryLogs () {
        console.log('进来看聊天记录了')
        const sender = this.memberSelectedInfo.userId
        const receiver = this.userInfo.userId

        chat.getPersonalHistoryLogs(sender, receiver).then(result => {
          if (result.code === 1) {
            result.data.forEach(item => {
              const msg = {
                userId: Number(item.sender),
                name: this.getName(item.sender),
                content: item.content,
                avatar: this.getAvatar(item.sender)
              }
              this.chatContent.push(msg)
            })
          }
          console.log('结结果111', result)
        }).catch(function (error) {
          console.log('错错错错误', error)
        })

        // const result = await chat.getPersonalHistoryLogs(sender, receiver)
        // if (result.code === 1) {
        //   result.data.forEach(item => {
        //     const msg = {
        //       userId: Number(item.sender),
        //       name: this.getName(item.sender),
        //       content: item.content,
        //       avatar: this.getAvatar(item.sender)
        //     }
        //     this.chatContent.push(msg)
        //   })
        // }
        // console.log('1111111', result)
      },
      getName(id){
        if(id===String(this.userInfo.userId)){
          return this.userInfo.detail.name
        }else {
          return this.memberSelectedInfo.detail.name
        }
      },
      getAvatar(id){
        if(id===String(this.userInfo.userId)){
          return this.userInfo.detail.avatar
        }else {
          return this.memberSelectedInfo.detail.avatar
        }
      }
    }
  }
</script>
<style scoped>
  * {
    -webkit-user-select: text;
  }

  .mainBg {
    margin-top: 46px;
    height: 100%;
    background: rgb(245, 245, 245);
  }

  .chat_view {
    height: 100%;
    width: 100%;

    /*background-color: red;*/
  }

  .message_box {
    width: 100%;
    background-color: white;
    padding: 0 10px;
    /*padding-bottom: 10px;*/
  }

  .chat_input {
    min-height: 70px;
    height: auto;
    width: 100%;
    position: fixed;
    bottom: 0;
    left: 0;
    background-color: white;
    vertical-align: bottom;
    border-top: #b2b2b2 solid 1px;
  }

  .input_box {
    display: inline-block;
    width: 65%;
    height: auto;
    min-height: 2rem;
    max-height: 10em;
    overflow: auto;
    padding: 5px 15px;
    margin: 10px;
    background-color: rgba(240, 248, 255, .6);
    border-radius: 20px;
    border: #b2b2b2 solid 1px;
  }

  .send_bt {
    display: inline-flex;
    /*width: 60px;*/
    line-height: 4rem;
    height: 4rem;
    text-align: center;
    vertical-align: top;
    border: 0;
    outline: 0;
    color: #35495E;
    background-color: white;
    font-size: 1.2rem;
  }

  .myHeadIcon {
    display: inline-block;
    width: 50px;
    height: 50px;
    margin-top: 0;
  }

  .content_view_box {
    display: inline-block;
    vertical-align: top;
    line-height: 20px;
    width: calc(100% - 80px);
    margin-right: 10px;
  }

  .left_head_box {
    display: inline-block;
    width: 50px;
    height: auto;
    padding: 0;
    text-align: center;
    margin-left: 5px;
    border: 0;
    background-color: rgb(245, 245, 245);
  }

  .left_triangle {
    display: inline-block;
    margin-left: -10px;
    margin-top: 10px;
    height: 0;
    width: 0;
    border: 10px solid transparent;
    border-right: 10px solid #faebcc;
  }

  .left_msg_box {
    display: inline-flex;
    padding: 10px;
    margin-left: -7px;
    background-color: #faebcc;
    border-radius: 5px;
    max-width: 85%;
    word-wrap: break-word;
    word-break: break-all;
  }

  .right_head_box {
    /*float: right;*/
    display: inline-block;
    margin-left: 80%;
    margin-right: 15px;
    width: 50px;
    height: auto;
    padding: 0;
    text-align: center;
    border: 0;
    background-color: rgb(245, 245, 245);
  }

  .right_triangle {
    float: right;
    margin-right: 1px;
    display: inline-block;
    /*margin-left: calc( 80% - 5px);*/
    margin-top: -60px;
    height: 0;
    width: 0;
    border: 10px solid transparent;
    border-left: 10px solid #c0e5f7;
  }


  .right_msg_box {
    display: inline-flex;
    margin-top: -65px;
    float: right;
    margin-right: calc(1% + 15px);
    /*margin-left: calc( 80% - 8px);*/
    padding: 10px;
    /*background-color: white;*/
    border-radius: 5px;
    max-width: 85%;
    word-wrap: break-word;
    word-break: break-all;
    background-color: #c0e5f7;
  }

  .content_time {
    margin: 5px;
    text-align: center;
    color: #b2b2b2;
    /*font-family: "微軟正黑體 Light";*/
    font-size: small;
  }

  .to_bottom {
    position: fixed;
  }

  div {
    outline: none;
  }
</style>
